import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

// 白名单
import router from "@/router/index.js";
import {getStore} from "@/utils/util.js";
import {LoginService} from "@/api/login.js";

NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/register'];

// 处理动态路由刷新白屏
let isLoadRouters = false;
router.beforeEach(async (to, from, next) => {
    NProgress.start();
    // 判断token
    if (getStore('token')) {
        /* 存在token */
        if (to.path === '/login') {
            next('/');
            NProgress.done();
        } else if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            if (isLoadRouters) {
                next();
            } else {
                isLoadRouters = true;
                // 处理动态路由刷新白屏
                // 因为异步问题
                await LoginService.getRouters()
                next({...to})
            }
        }
    } else {
        /* 不存在token */
        if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            next('/login');
            NProgress.done();
        }
    }
})

router.afterEach(()=>{
    NProgress.done();
})
